//
//  ViewChapterOffline.m
//  CMS
//
//  Created by Vuong Van Khanh on 12/14/12.
//  Copyright (c) 2012 Rikkei. All rights reserved.
//

#import "ViewChapterOffline.h"
#import "StoreVars.h"
#import "customCells.h"
#import "ReaderViewController.h"

@implementation ViewChapterOffline
@synthesize contentLink;

- (void) alertStatus:(NSString *)msg :(NSString *)title
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];
    
    [alertView show];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    numberOfChapter = 0;
    numberOfDeletedRows = 0;
    indexPathsForDelete = [[NSMutableArray alloc] init];
    
    //get all folder of content in user's directory
    if(contentLink){
        pathToChapter = [[NSString alloc] initWithFormat:@"%@/%@", [StoreVars sharedInstance].downloadDir, contentLink];
        NSArray *dirContents = [[NSFileManager defaultManager] subpathsAtPath:pathToChapter];
        NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self CONTAINS 'chapters.xml'"];
        folderNameArray = [dirContents filteredArrayUsingPredicate:fltr];
        numberOfChapter = [folderNameArray count];
    }
    UIButton *backButton = [UIButton buttonWithType:101];
    [backButton setTitle:@"Content" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToContent:) forControlEvents:UIControlEventTouchUpInside];
    
    backToContentButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.navigationItem.leftBarButtonItem = backToContentButton;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return numberOfChapter - numberOfDeletedRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellChapterOffline";
    
    customCells *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[customCells alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    // Configure the cell...
    NSString *title = [[folderNameArray objectAtIndex:indexPath.row] stringByDeletingLastPathComponent];
    cell.title.text = [[NSFileManager defaultManager] displayNameAtPath:title];
    NSString *pathToPDF = [NSString stringWithFormat:@"%@/%@", pathToChapter, title];
    cell.downloadLink.text = pathToPDF;
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.editing)
    {
        [indexPathsForDelete addObject:indexPath];
        return;
    }
    customCells *cell = (customCells *)[self.tableView cellForRowAtIndexPath:indexPath];
    // Navigation logic may go here. Create and push another view controller.
    ReaderViewController *reader = [[UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle:nil] instantiateViewControllerWithIdentifier:@"ViewDetailController"];
    reader.pathToPDF = cell.downloadLink.text;
    [self.navigationController pushViewController:reader animated:YES];

}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.editing)
    {
        [indexPathsForDelete removeObject:indexPath];
    }
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animate {
    self.tableView.allowsMultipleSelectionDuringEditing = editing;
    [super setEditing:editing animated:animate];
    
    if(editing)
    {
        self.editButtonItem.title = @"Delete";
        cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonPress:)];
        self.navigationItem.leftBarButtonItem = cancelButton;
    }
    else
    {
        //Delete selected items if exits
        if(indexPathsForDelete){
            // add number of delete rows
            numberOfDeletedRows += [indexPathsForDelete count];
            
            //delete content's folder
            NSString *msg = nil;
            for(int i =0; i< numberOfDeletedRows; i++){
                NSIndexPath *indexPath = [indexPathsForDelete objectAtIndex:i];
                customCells *cell = (customCells *) [self.tableView cellForRowAtIndexPath:indexPath];
                NSString *folderPath = [[NSString alloc] initWithFormat:@"%@/%@/%@", [StoreVars sharedInstance].downloadDir, contentLink, cell.title.text];
                if ([[NSFileManager defaultManager] removeItemAtPath:folderPath error: nil] == NO)
                {
                    [msg stringByAppendingFormat:@"%@ ", cell.title.text];
                }
            }
            if(msg) {
                NSString *alertMsg = [[NSString alloc] initWithFormat:@"%@ %@", msg, @"unable to delete"];
                [self alertStatus:alertMsg :@"Warning"];
            }
            
            //update to Table view
            [self.tableView deleteRowsAtIndexPaths:indexPathsForDelete withRowAnimation:UITableViewRowAnimationFade];
            
            //release indexPaths array
            [indexPathsForDelete removeAllObjects];
        }
        
        // set server button again
        self.navigationItem.leftBarButtonItem = backToContentButton;
    }
}
- (IBAction)cancelButtonPress:(id)sender {
    //release indexPaths array
    [indexPathsForDelete removeAllObjects];
    
    [self setEditing:NO animated:YES];
}

- (IBAction)logoutButtonClicked:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (IBAction)backToContent:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
